import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'QuestionGenerator.dart';
import 'dart:math';

class ExamPage extends StatefulWidget {

  @override
  _ExamPageState createState() => _ExamPageState();
}

class _ExamPageState extends State<ExamPage> {

  final List<String> _userAnswers = [];
  final List<TextEditingController> controllers=[];
  List<Map<String, dynamic>> questions = [];
  bool isLoading = true;  // 加载标志
  bool isSubmitted = false;
  List<bool>isRights=[];

  @override
  void initState() {
    super.initState();

    generateQuestions(1,50);
    // 重置用户答案为空字符串列表，长度与题目数量一致
    _userAnswers.clear();
    _userAnswers.addAll(List.filled(50, ''));
  }

  // 发送请求获取错题
  Future<void> generateQuestions(int userId,int num) async{
    const apiUrl = 'http://101.34.58.190:8080/api/exercise/generate';
    final url = Uri.parse('$apiUrl?userId=$userId&num=$num');
    try {
      final response = await http.get(url);
      if (response.statusCode == 200) {
        final data = json.decode(response.body);

        // 提取 API 返回的数据
        final List<Map<String, dynamic>> newQuestions = [];
        final List<TextEditingController> newControllers = [];
        for (var item in data['exercises']) {
          newQuestions.add({
            "realAns": item["realAns"], // 从外部字段获取
            "type": item["type"],               // 从每个题目获取
            "express": item["express"],            // 题目表达式
          });
          newControllers.add(TextEditingController());
        }
        setState(() {
          controllers..clear()..addAll(newControllers);
          questions..clear()..addAll(newQuestions);
          isLoading=false;
        });


      } else {
        throw Exception('Failed to load questions');
      }
    } catch (e) {
      print('获取题目失败: $e');
    }
    // print('\x1B[31m${questions}\x1B[0m');
    // print('\x1B[31m${controllers.length}\x1B[0m');
    // print('\x1B[31m------------------------------------------\n\x1B[0m');
  }

  // 显示试卷题目
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("试卷题目")),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: isLoading
            ? Center(child: CircularProgressIndicator()) // 显示加载中提示
            : Column(
          children: [
            // 显示问题列表
            Expanded(
              child: ListView.builder(
                shrinkWrap: true, // 避免无限高度错误
                //physics: const NeverScrollableScrollPhysics(), // 禁用内层滚动
                itemCount: questions.length,
                itemBuilder: (context, index) {
                  final question = questions[index];
                  // 在 submissionResults 中查找对应题目
                  bool? isRight;
                  if(isRights.isEmpty){
                    isRight=null;
                  }
                  else{
                    isRight=isRights[index];
                  }
                  final backgroundColor = isRight == true
                      ? Colors.green.shade300
                      : isRight == false
                      ? Colors.red.shade300
                      : Colors.white;
                  return Card(
                    margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                    elevation: 2,
                    color: backgroundColor, // 动态背景颜色
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text(
                              '${index + 1}: ${question["express"]}', // 展示题目
                              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                            ),
                          ),
                          SizedBox(
                            width: 80,
                            child: TextField(
                              controller: controllers[index], // 使用对应的 Controller
                              keyboardType: TextInputType.number,
                              decoration: InputDecoration(
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(8),
                                ),
                              ),
                              onChanged: (value) {
                                updateAnswer(index, value); // 更新答案
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
            // 提交答案按钮
            Center(
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.green.shade400,
                  padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 32),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                ),
                onPressed: () {
                  _submitAndMarkAsSubmitted(); // 没有未作答，直接提交
                },
                child: const Text(
                  '提交答案',
                  style: TextStyle(fontSize: 16, color: Colors.white),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
  void updateAnswer(int index, String value) {
    setState(() {
      _userAnswers[index] = value;
      controllers[index].text = value;
    });
  }

  void _submitAndMarkAsSubmitted() async {
    setState(() {
      isSubmitted = true;   // 标记已提交
      int i=0;
      bool isRight=false;
      for(var item in questions){
          if(item["realAns"].trim()==controllers[i].text.trim()){
            isRight=true;
          }
          else{
            isRight=false;
          }
          isRights.add(isRight);
          i++;
      }
    });
  }
}
